#  Copyright 2012 Eric Lawrey, Australian Institute of Marine Science
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

# Performs a multiple find and replace on the template, finding all the occurances of the
# dataNames (delimited by $[dataName]) and replacing them with their corresponding dataValues.
# preName, postName:		These are added to the start and end of the dataNames before performing
#					the search. They must be suitable for use in a regular expression.
replaceText <- function (template, dataNames, dataValues, preName="\\{", postName="\\}") {
	if (length(dataNames) != length(dataValues)) {
		dataNamePreview <- paste(dataNames[1:min(length(dataNames),3)], collapse=",")
		dataValuesPreview <- paste(dataValues[1:min(length(dataValues),3)], collapse=",")
		warningStr <- paste("length of ",
			"dataNames (", length(dataNames), ":", dataNamePreview, ") and ",
			"dataValues (", length(dataValues), ":", dataValuesPreview, ") ",
			"don't match", sep="")
		warning(warningStr)
	}
	for (i in 1:length(dataNames)) {
		# Escape any dots in the dataNames
		pattern <- paste(preName, gsub("\\.","\\\\.", dataNames[i]), postName, sep="")
		# Convert NA values to "NA" string otherwise the gsub
		# will return NA, rather than the desired effect of replacing
		# the name field with "NA"
		if (is.na(dataValues[i])) {
			replacement <- "NA"
		} else {
			replacement <- dataValues[i]
		}
		template <- gsub(pattern, replacement, template)
	}
	return(template)
}
